package com.xxxtea.sdk.alipay;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.io.FileUtil;
import com.alibaba.fastjson2.JSON;
import com.alipay.api.*;
import com.alipay.api.internal.util.AlipaySignature;
import com.alipay.api.request.AlipayTradePagePayRequest;
import lombok.SneakyThrows;
import org.springframework.stereotype.Service;

import javax.annotation.PostConstruct;
import javax.annotation.Resource;
import java.io.File;
import java.util.HashMap;

/**
 * 支付宝支付服务类
 * 
 * 封装支付宝支付相关的操作，包括：
 * - 支付宝客户端初始化
 * - 网页支付请求
 * - 支付回调验签
 * 
 * @author badman
 * @since 1.0.0
 */
@Service
public class AliPayService {
	/**
	 * 支付宝客户端
	 */
	private AlipayClient alipayClient;
	/**
	 * 支付宝配置属性
	 */
	@Resource
	private AliPayProperties aliPayProperties;

	/**
	 * 初始化支付宝客户端
	 * 
	 * 在Bean创建后自动调用，配置支付宝SDK参数
	 * @throws AlipayApiException 初始化失败时抛出
	 */
	@PostConstruct
	public void init() throws AlipayApiException {
		AlipayConfig alipayConfig = BeanUtil.toBean(aliPayProperties, AlipayConfig.class);
		alipayConfig.setServerUrl("https://openapi-sandbox.dl.alipaydev.com/gateway.do");
		this.alipayClient = new DefaultAlipayClient(alipayConfig);
	}

	/**
	 * 网页支付请求
	 * 
	 * 构建并发送支付宝网页支付请求，将返回的HTML写入本地文件（仅用于测试）
	 * @param payRequest 支付请求参数
	 */
	@SneakyThrows
	public void pay(PayRequest payRequest) {
		AlipayTradePagePayRequest request = new AlipayTradePagePayRequest();
		request.setNotifyUrl(aliPayProperties.getNotifyUrl());
		request.setBizContent(JSON.toJSONString(payRequest));
		AlipayResponse response = alipayClient.pageExecute(request);
		FileUtil.writeUtf8String(response.getBody(), new File("1.html"));
	}

	/**
	 * 支付回调验签
	 * 
	 * 验证支付宝回调通知的签名合法性
	 */
	@SneakyThrows
	public void notifyOrder() {
		boolean signVerified = AlipaySignature.rsaCheckV1(new HashMap<>(), aliPayProperties.getAlipayPublicKey(), "UTF-8", "RSA2");
	}

}
